<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <el-card class="filter-container">
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <el-form-item label="关键词">
          <el-input
            v-model="queryParams.keyword"
            placeholder="请输入商家名称/联系人/电话"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
            <el-option label="待审核" :value="2" />
            <el-option label="正常" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="loading" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card>
      <el-table v-loading="loading" :data="merchantList">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="shopName" label="商家名称" />
        <el-table-column prop="legalPerson" label="法人" />
        <el-table-column prop="contactPhone" label="联系电话" />
        <el-table-column prop="status" label="状态">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleView(row)">查看</el-button>
            <el-button type="success" link @click="handleProducts(row)">商品管理</el-button>

            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              :loading="row.statusLoading"
              :disabled="row.status === 2"
              @change="handleStatusChange(row)"
              style="margin: 0 10px"
            />
            <el-button 
              type="primary" 
              link 
              @click="handleAudit(row)"
              v-if="row.status === 2"
            >
              审核
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 商家详情对话框 -->
    <el-dialog
      title="商家详情"
      v-model="detailDialogVisible"
      width="800px"
      :close-on-click-modal="false"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="商家名称">{{ merchantDetail.shopName }}</el-descriptions-item>
        <el-descriptions-item label="法人">{{ merchantDetail.legalPerson }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ merchantDetail.contactPhone }}</el-descriptions-item>
        <el-descriptions-item label="联系邮箱">{{ merchantDetail.contactEmail }}</el-descriptions-item>
        <el-descriptions-item label="商家地址">{{ merchantDetail.address }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusType(merchantDetail.status)">
            {{ getStatusText(merchantDetail.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ merchantDetail.createTime }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ merchantDetail.updateTime }}</el-descriptions-item>
        <el-descriptions-item label="营业执照" :span="2">
          <el-image 
            v-if="merchantDetail.businessLicense"
            :src="merchantDetail.businessLicense" 
            :preview-src-list="[merchantDetail.businessLicense]"
            fit="contain"
            style="max-width: 200px; max-height: 200px;"
          />
          <span v-else>暂无营业执照</span>
        </el-descriptions-item>
        <el-descriptions-item label="商家简介" :span="2">
          {{ merchantDetail.shopDesc || '暂无简介' }}
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 商家表单对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="merchantFormRef"
        :model="merchantForm"
        :rules="merchantRules"
        label-width="100px"
      >
        <el-form-item label="商家名称" prop="shopName">
          <el-input v-model="merchantForm.shopName" />
        </el-form-item>
        <el-form-item label="法人" prop="legalPerson">
          <el-input v-model="merchantForm.legalPerson" />
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="merchantForm.contactPhone" />
        </el-form-item>
        <el-form-item label="联系邮箱" prop="contactEmail">
          <el-input v-model="merchantForm.contactEmail" />
        </el-form-item>
        <el-form-item label="商家地址" prop="address">
          <el-input v-model="merchantForm.address" />
        </el-form-item>
        <el-form-item label="营业执照" prop="businessLicense">
          <el-input v-model="merchantForm.businessLicense" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 审核对话框 -->
    <el-dialog
      title="商家审核"
      v-model="auditDialogVisible"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="auditFormRef"
        :model="auditForm"
        :rules="auditRules"
        label-width="100px"
      >
        <el-form-item label="审核结果" prop="status">
          <el-radio-group v-model="auditForm.status">
            <el-radio :label="1">通过</el-radio>
            <el-radio :label="2">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核备注" prop="comment">
          <el-input
            v-model="auditForm.comment"
            type="textarea"
            :rows="3"
            placeholder="请输入审核备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="auditDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAuditSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { 
  getMerchantList, 
  updateMerchant, 
  updateMerchantStatus,
  auditMerchant,
  getMerchantDetail,
  searchMerchants
} from '@/api/admin'
import { useRouter } from 'vue-router'

const router = useRouter()

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  keyword: '',
  status: undefined
})

// 数据列表
const loading = ref(false)
const merchantList = ref([])
const total = ref(0)

// 表单对话框
const dialogVisible = ref(false)
const dialogTitle = ref('')
const merchantFormRef = ref()
const merchantForm = reactive({
  id: undefined,
  shopName: '',
  legalPerson: '',
  contactPhone: '',
  contactEmail: '',
  address: '',
  businessLicense: ''
})

// 表单验证规则
const merchantRules = {
  shopName: [{ required: true, message: '请输入商家名称', trigger: 'blur' }],
  legalPerson: [{ required: true, message: '请输入法人', trigger: 'blur' }],
  contactPhone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
  contactEmail: [{ required: true, message: '请输入联系邮箱', trigger: 'blur' }],
  address: [{ required: true, message: '请输入商家地址', trigger: 'blur' }],
  businessLicense: [{ required: true, message: '请输入营业执照', trigger: 'blur' }]
}

// 审核对话框
const auditDialogVisible = ref(false)
const auditFormRef = ref()
const auditForm = reactive({
  id: undefined,
  status: 1,
  comment: ''
})

// 审核表单验证规则
const auditRules = {
  status: [{ required: true, message: '请选择审核结果', trigger: 'change' }]
}

// 详情对话框
const detailDialogVisible = ref(false)
const merchantDetail = ref({})

// 获取商家列表
const getList = async () => {
  loading.value = true
  try {
    let res
    if (queryParams.keyword) {
      // 如果有关键词，使用搜索接口
      res = await searchMerchants(queryParams)
      // 搜索接口返回的是数组
      merchantList.value = (res.data || []).map(item => ({
        ...item,
        statusLoading: false
      }))
      total.value = res.data?.length || 0
    } else {
      // 普通列表接口返回分页数据
      res = await getMerchantList(queryParams)
      // 从 data.records 中获取列表数据
      merchantList.value = (res.data?.records || []).map(item => ({
        ...item,
        statusLoading: false
      }))
      total.value = res.data?.total || 0
    }
  } catch (error) {
    console.error('获取商家列表失败:', error)
    ElMessage.error(error.message || '获取商家列表失败')
    merchantList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 查询
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置查询
const resetQuery = () => {
  queryParams.keyword = ''
  queryParams.status = undefined
  handleQuery()
}

// 分页大小改变
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  getList()
}

// 页码改变
const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  getList()
}

// 编辑商家
const handleEdit = (row) => {
  dialogTitle.value = '编辑商家'
  dialogVisible.value = true
  Object.assign(merchantForm, row)
}

// 提交表单
const handleSubmit = async () => {
  if (!merchantFormRef.value) return
  await merchantFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (merchantForm.id) {
          await updateMerchant(merchantForm.id, merchantForm)
          ElMessage.success('更新成功')
        }
        dialogVisible.value = false
        getList()
      } catch (error) {
        console.error('保存失败:', error)
      }
    }
  })
}

// 状态映射函数
const getStatusType = (status) => {
  switch (status) {
    case 1: return 'success'  // 启用
    case 0: return 'danger'   // 禁用
    case 2: return 'warning'  // 待审核
    default: return 'info'
  }
}

const getStatusText = (status) => {
  switch (status) {
    case 1: return '正常'
    case 0: return '禁用'
    case 2: return '待审核'
    default: return '未知'
  }
}

// 处理状态切换
const handleStatusChange = async (row) => {
  try {
    const confirmMessage = row.status === 0 ? '确定要启用该商家吗？' : '确定要禁用该商家吗？'
    await ElMessageBox.confirm(confirmMessage, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const loading = ElLoading.service({
      lock: true,
      text: '正在更新状态...',
      background: 'rgba(0, 0, 0, 0.7)'
    })

    try {
      // 直接使用当前的 row.status，因为 el-switch 已经更新了状态值
      await updateMerchantStatus(row.id, row.status)
      ElMessage.success('状态更新成功')
      // 更新成功后刷新列表
      await getList()
    } catch (error) {
      console.error('Status update error:', error)
      // 如果更新失败，恢复原来的状态
      row.status = row.status === 0 ? 1 : 0
      ElMessage.error(error.message || '状态更新失败，请重试')
    } finally {
      loading.close()
    }
  } catch {
    // 用户取消操作，恢复原来的状态
    row.status = row.status === 0 ? 1 : 0
  }
}

// 审核商家
const handleAudit = (row) => {
  auditForm.id = row.id
  auditForm.status = 1
  auditForm.comment = ''
  auditDialogVisible.value = true
}

// 提交审核
const handleAuditSubmit = async () => {
  if (!auditFormRef.value) return
  await auditFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await auditMerchant(auditForm.id, {
          status: auditForm.status,
          comment: auditForm.comment
        })
        ElMessage.success('审核成功')
        auditDialogVisible.value = false
        getList()
      } catch (error) {
        console.error('审核失败:', error)
      }
    }
  })
}

// 查看商家详情
const handleView = async (row) => {
  try {
    const res = await getMerchantDetail(row.id)
    merchantDetail.value = res
    detailDialogVisible.value = true
  } catch (error) {
    console.error('获取商家详情失败:', error)
    ElMessage.error('获取商家详情失败')
  }
}

// 跳转到商品管理页面
const handleProducts = (row) => {
  router.push(`/admin/product/list/${row.id}`)
}

onMounted(() => {
  getList()
})
</script>

<style scoped>
.filter-container {
  margin-bottom: 20px;
}
.operate-container {
  margin-bottom: 20px;
}
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 